package com.yuanrui.circle.server.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanrui.circle.api.common.PageInfo;
import com.yuanrui.circle.api.common.PageResult;
import com.yuanrui.circle.api.enums.IsDeletedFlagEnum;
import com.yuanrui.circle.api.req.GetShareMessageReq;
import com.yuanrui.circle.api.vo.ShareMessageVO;
import com.yuanrui.circle.server.dao.ShareMessageDao;
import com.yuanrui.circle.server.entity.ShareMessage;
import com.yuanrui.circle.server.rpc.UserRpc;
import com.yuanrui.circle.server.service.ShareMessageService;
import com.yuanrui.circle.server.util.LoginUtil;
import com.yuanrui.circle.server.websocket.ChickenSocket;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 消息表(ShareMessage)表服务实现类
 *
 * @author makejava
 * @since 2024-07-28 16:15:01
 */
@Service("shareMessageService")
public class ShareMessageServiceImpl extends ServiceImpl<ShareMessageDao, ShareMessage> implements ShareMessageService {
    @Resource
    private ShareMessageDao shareMessageDao;
    @Resource
    private UserRpc userRpc;

    @Resource
    private ChickenSocket chickenSocket;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public ShareMessage queryById(Integer id) {
        return this.shareMessageDao.queryById(id);
    }


    /**
     * 新增数据
     *
     * @param shareMessage 实例对象
     * @return 实例对象
     */
    @Override
    public ShareMessage insert(ShareMessage shareMessage) {
        this.shareMessageDao.insert(shareMessage);
        return shareMessage;
    }

    /**
     * 修改数据
     *
     * @param shareMessage 实例对象
     * @return 实例对象
     */
    @Override
    public ShareMessage update(ShareMessage shareMessage) {
        this.shareMessageDao.update(shareMessage);
        return this.queryById(shareMessage.getId().intValue());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.shareMessageDao.deleteById(id) > 0;
    }

    @Override
    public int comment(String fromId, String toId, Long targetId) {
        JSONObject message = new JSONObject();
        // 1=评论 2=回复
        message.put("msgType", "COMMENT");
        message.put("msg", String.format("%s 评论了你的内容，快来看看把！", userRpc.getUserInfo(fromId).getNickName()));
        message.put("targetId", targetId);
        ShareMessage shareMessage = new ShareMessage();
        shareMessage.setFromId(fromId);
        shareMessage.setToId(toId);
        shareMessage.setContent(message.toJSONString());
        shareMessage.setIsRead(2);
        shareMessage.setCreatedBy(fromId);
        shareMessage.setCreatedTime(new Date());
        shareMessage.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        ChickenSocket socket = chickenSocket.getChickenSocket(toId);
        if (Objects.nonNull(socket)) {
            chickenSocket.sendMessage(shareMessage.getContent(), socket.getSession());
        }
        return super.save(shareMessage) ? 1 : 0;
    }

    @Override
    public int reply(String fromId, String toId, Long targetId) {
        JSONObject message = new JSONObject();
        // 1=评论 2=回复
        message.put("msgType", "COMMENT_REPLY");
        message.put("msg", String.format("%s 回复了你的评论，快来看看把！", userRpc.getUserInfo(fromId).getNickName()));
        message.put("targetId", targetId);
        ShareMessage shareMessage = new ShareMessage();
        shareMessage.setFromId(fromId);
        shareMessage.setToId(toId);
        shareMessage.setContent(message.toJSONString());
        shareMessage.setIsRead(2);
        shareMessage.setCreatedBy(fromId);
        shareMessage.setCreatedTime(new Date());
        shareMessage.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        ChickenSocket socket = chickenSocket.getChickenSocket(toId);
        if (Objects.nonNull(socket)) {
            chickenSocket.sendMessage(shareMessage.getContent(), socket.getSession());
        }
        return super.save(shareMessage) ? 1 : 0;
    }

    @Override
    public boolean unRead() {
        LambdaQueryWrapper<ShareMessage> query = Wrappers.<ShareMessage>lambdaQuery()
                .eq(ShareMessage::getToId, LoginUtil.getLoginId())
                .eq(ShareMessage::getIsRead, 2)
                .eq(ShareMessage::getIsDeleted, IsDeletedFlagEnum.UN_DELETED.getCode());
        return super.count(query) > 0;
    }

    @Override
    public PageResult<ShareMessageVO> getMessages(GetShareMessageReq req) {
        LambdaQueryWrapper<ShareMessage> query = Wrappers.<ShareMessage>lambdaQuery()
                .eq(ShareMessage::getToId, LoginUtil.getLoginId())
                .eq(ShareMessage::getIsRead, req.getIsRead())
                .eq(ShareMessage::getIsDeleted, IsDeletedFlagEnum.UN_DELETED.getCode())
                .orderByDesc(ShareMessage::getId);
        PageInfo pageInfo = req.getPageInfo();
        Page<ShareMessage> page = new Page<>(pageInfo.getPageNo(), pageInfo.getPageSize());
        Page<ShareMessage> pageRes = super.page(page, query);
        PageResult<ShareMessageVO> result = new PageResult<>();
        List<ShareMessage> records = pageRes.getRecords();
        if (CollectionUtils.isNotEmpty(records)) {
            List<Long> ids = records.stream().map(ShareMessage::getId).collect(Collectors.toList());
            LambdaUpdateWrapper<ShareMessage> update = Wrappers.<ShareMessage>lambdaUpdate().set(ShareMessage::getIsRead, 1).in(ShareMessage::getId, ids);
            super.update(update);
        }
        List<ShareMessageVO> list = records.stream().map(item -> {
            ShareMessageVO vo = new ShareMessageVO();
            vo.setId(item.getId());
            vo.setContent(JSON.parseObject(item.getContent()));
            vo.setCreatedTime(item.getCreatedTime());
            return vo;
        }).collect(Collectors.toList());
        result.setResult(list);
        result.setTotal((int) pageRes.getTotal());
        result.setPageSize(pageInfo.getPageSize());
        result.setPageNo(pageInfo.getPageNo());
        return result;
    }
}
